const { prisma } = require('../config/prisma');
const { CozeService } = require('../services/coze.service');

const generateExercise = async (req, res) => {
  try {
    const { type, chars, unit_id, image_url, difficulty = 1, style = 1 } = req.body;
    console.log('Generating exercise with params:', { type, chars, unit_id, image_url, difficulty, style });

    // 验证输入参数
    if (type === 1 && (!chars || chars.length !== 6)) {
      return res.status(400).json({
        code: 400,
        message: '请提供6个汉字'
      });
    }

    if (type === 2 && (!unit_id || isNaN(unit_id))) {
      return res.status(400).json({
        code: 400,
        message: 'Unit ID must be a positive number'
      });
    }

    // 获取积分配置
    const pointsConfig = await prisma.systemConfig.findUnique({
      where: { key: 'points_exercise' }
    });
    
    if (!pointsConfig) {
      throw new Error('Points configuration not found');
    }

    const { daily_limit, points_per_exercise } = JSON.parse(pointsConfig.value);

    // 检查每日积分获取情况
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayPoints = await prisma.pointsRecord.aggregate({
      where: {
        userId: req.user.id,
        type: 1,
        createdAt: {
          gte: today
        }
      },
      _sum: {
        points: true
      }
    });

    const earnedPoints = todayPoints._sum.points || 0;
    console.log('Daily points check:', { earnedPoints, daily_limit });

    if (earnedPoints >= daily_limit) {
      return res.status(400).json({
        code: 1002,
        message: 'Daily points limit reached'
      });
    }

    // 调用 Coze API 生成练习
    console.log('Calling Coze API with params:', { type, chars, unit_id, image_url, difficulty, style });
    const cozeServiceInstance = new CozeService();
    const exerciseData = await cozeServiceInstance.generateExercise({ type, chars, unit_id, image_url, difficulty, style });
    
    console.log('Raw Coze response:', exerciseData);

    // 解析 Coze API 返回的数据
    let parsedData;
    try {
      // 从不同可能的位置获取 base_chars
      const base_chars = exerciseData.base_chars || [];
      
      // 获取练习内容
      const content = exerciseData.content || {};
      
      // 构建解析后的数据
      parsedData = {
        base_chars,
        level_1: content.level_1 || [],
        level_2: content.level_2 || [],
        level_3: content.level_3 || [],
        level_4: content.level_4 || [],
        audio_url_1: exerciseData.audio_url_1,
        audio_url_2: exerciseData.audio_url_2,
        audio_url_3: exerciseData.audio_url_3,
        audio_url_4: exerciseData.audio_url_4
      };

      console.log('Parsed data:', parsedData);

      // 确保数据格式正确
      if (!Array.isArray(parsedData.base_chars) || parsedData.base_chars.length === 0) {
        console.error('Missing base_chars in API response:', exerciseData);
        throw new Error('练习数据格式错误：缺少基础汉字数据');
      }

      if (!Array.isArray(parsedData.level_1) || parsedData.level_1.length === 0) {
        console.error('Missing level_1 data in API response:', exerciseData);
        throw new Error('练习数据格式错误：缺少练习内容');
      }

      // 创建练习记录
      const exercise = await prisma.exerciseRecord.create({
        data: {
          userId: req.user.id,
          baseChars: parsedData.base_chars,
          difficulty,
          style,
          content: {
            level_1: parsedData.level_1,
            level_2: parsedData.level_2,
            level_3: parsedData.level_3,
            level_4: parsedData.level_4
          },
          audioUrl1: parsedData.audio_url_1,
          audioUrl2: parsedData.audio_url_2,
          audioUrl3: parsedData.audio_url_3,
          audioUrl4: parsedData.audio_url_4
        }
      });

      console.log('Created exercise record:', exercise);

      // 如果未达到每日积分上限，添加积分记录
      if (earnedPoints < daily_limit) {
        const pointsToAdd = Math.min(points_per_exercise, daily_limit - earnedPoints);
        const pointsRecord = await prisma.pointsRecord.create({
          data: {
            userId: req.user.id,
            points: pointsToAdd,
            type: 1,
            remark: '生成练习题'
          }
        });
        console.log('Created points record:', pointsRecord);

        // 更新用户积分
        const user = await prisma.user.update({
          where: { id: req.user.id },
          data: {
            points: {
              increment: pointsToAdd
            }
          }
        });
        console.log('Updated user points:', user.points);
      }

      // 返回响应
      res.json({
        code: 0,
        data: {
          id: exercise.id,
          userId: exercise.userId,
          baseChars: exercise.baseChars,
          difficulty: exercise.difficulty,
          style: exercise.style,
          content: exercise.content,
          audioUrl1: exercise.audioUrl1,
          audioUrl2: exercise.audioUrl2,
          audioUrl3: exercise.audioUrl3,
          audioUrl4: exercise.audioUrl4,
          createdAt: exercise.createdAt
        }
      });
    } catch (error) {
      console.error('Generate exercise error:', error);
      if (error.message === 'Points configuration not found') {
        return res.status(500).json({
          code: 500,
          message: '系统配置错误'
        });
      }
      res.status(500).json({
        code: 500,
        message: error.message || '生成练习题失败'
      });
    }
  } catch (error) {
    console.error('Generate exercise error:', error);
    if (error.message === 'Points configuration not found') {
      return res.status(500).json({
        code: 500,
        message: '系统配置错误'
      });
    }
    res.status(500).json({
      code: 500,
      message: error.message || '生成练习题失败'
    });
  }
};

const shuffleExercise = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 获取原练习记录
    const exercise = await prisma.exerciseRecord.findFirst({
      where: {
        id,
        userId
      }
    });

    if (!exercise) {
      return res.status(404).json({
        code: 404,
        message: '练习记录不存在'
      });
    }

    // 调用 Coze API 打乱内容并生成新的音频
    const cozeServiceInstance = new CozeService();
    const response = await cozeServiceInstance.shuffleExercise({
      base_chars: exercise.baseChars,
      content: exercise.content,
      style: exercise.style
    });

    // 确保 response.content 存在
    if (!response.content) {
      throw new Error('打乱练习返回的内容格式不正确');
    }

    // 更新练习记录
    const updatedExercise = await prisma.exerciseRecord.update({
      where: { id },
      data: {
        content: response.content,
        audioUrl1: response.audio_url_1,
        audioUrl2: response.audio_url_2,
        audioUrl3: response.audio_url_3,
        audioUrl4: response.audio_url_4
      }
    });

    // 返回响应
    res.json({
      code: 0,
      data: {
        id: updatedExercise.id,
        baseChars: updatedExercise.baseChars,
        content: updatedExercise.content,
        audioUrl1: updatedExercise.audioUrl1,
        audioUrl2: updatedExercise.audioUrl2,
        audioUrl3: updatedExercise.audioUrl3,
        audioUrl4: updatedExercise.audioUrl4
      }
    });
  } catch (error) {
    console.error('Shuffle exercise error:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '打乱练习题失败'
    });
  }
};

const getHistory = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const size = parseInt(req.query.size) || 20;
    const userId = req.user.id;
    const skip = (page - 1) * size;

    const [total, records] = await Promise.all([
      prisma.exerciseRecord.count({
        where: { userId }
      }),
      prisma.exerciseRecord.findMany({
        where: { userId },
        orderBy: { createdAt: 'desc' },
        skip,
        take: size,
      })
    ]);

    res.json({
      code: 0,
      data: {
        total,
        list: records.map(record => ({
          id: record.id,
          base_chars: record.baseChars,  // 直接使用，不需要 JSON.parse
          difficulty: record.difficulty,
          created_at: record.createdAt,
          content: record.content,
          audio_url_1: record.audioUrl1,
          audio_url_2: record.audioUrl2,
          audio_url_3: record.audioUrl3,
          audio_url_4: record.audioUrl4
        }))
      }
    });
  } catch (error) {
    console.error('Get exercise history error:', error);
    res.status(500).json({
      code: 500,
      message: 'Failed to get exercise history'
    });
  }
};

const deleteHistory = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const exercise = await prisma.exerciseRecord.findFirst({
      where: {
        id,
        userId
      }
    });

    if (!exercise) {
      return res.status(404).json({
        code: 404,
        message: 'Exercise not found'
      });
    }

    await prisma.exerciseRecord.delete({
      where: { id }
    });

    res.json({
      code: 0,
      message: 'Exercise deleted successfully'
    });
  } catch (error) {
    console.error('Delete exercise error:', error);
    res.status(500).json({
      code: 500,
      message: 'Failed to delete exercise'
    });
  }
};

module.exports = {
  generateExercise,
  shuffleExercise,
  getHistory,
  deleteHistory
}; 